package cn.edu.dgut.experiment3.dao;

import cn.edu.dgut.experiment3.pojo.Region;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableScheduling
public class RegionDao {

    final static String URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    public final static List<Region> dataList = new ArrayList<>();
    public final static List<Region> searchList = new ArrayList<>();

    public List<Region> getDatalist(){
        return dataList;
    }

    //获取数据
    @Scheduled(cron = "${yzm.Schedules.updateVirusDateCron}")
    public void pullData() throws IOException {

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity,Resource.class);
        Resource body = exchange.getBody();

        if ( body!=null ) {
            final Reader reader = new InputStreamReader(body.getInputStream());
            final CSVParser pasre = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
            for ( CSVRecord record : pasre) {
                dataList.add(Region.builder()
                        .state(record.get(0))
                        .country(record.get(1))
                        .latestTotalCases(Integer.parseInt(record.get(record.size()-1)))
                        .diffFromPrevDay( (Integer.parseInt(record.get(record.size()-1))) - (Integer.parseInt(record.get(record.size()-2))))
                        .build());
            }
            reader.close();
        }
    }



    //遍历list集合，按国家名筛选数据
    public List<Region> getDataByCountry(String country){
        searchList.clear();
        for(Region data : dataList){
            if(data.getCountry().equals(country)){
                searchList.add(data);
            }
        }
        return searchList;
    }
}
